<template>
  <div class="echarts h-auto" :class="size == 'small' ? 'h-[220px]!' : ''">
    <ECharts
      v-if="option"
      :option="option"
      :id="`Line` + props.id"
      ref="lineEChartsRef"
      :onClick="handleClick"
    />
    <!-- 工单弹窗 -->
    <psmworkorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
      key="1"
    />
  </div>
</template>

<script lang="ts" setup>
import { getPieces, isGetPieces } from "@/views/pcm/pcmMonitoring/index";
import psmworkorderEdit from "@/views/pcm/psmworkorder/components/psmworkorder-edit.vue";
import request from "@/utils/request";
import Big from "big.js";
const props = defineProps({
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  size: {
    type: String,
    default: () => {
      return "";
    },
  },
  nameRotate: {
    type: Number,
    default: () => {
      return 45;
    },
  },
  showName: {
    type: Boolean,
    default: true,
  },
  // 曲线x轴/y轴数据
  seriesData: {
    type: Object,
    default: () => {
      return {
        paramName: "Journal C-Diameter (bottom)",
        upperLimitValue: 515,
        lowerLimitValue: 280,
        controlDown: 290,
        controlUp: 490,
        parameterStandards: 350,
        xdataIndex: [
          "1",
          "2",
          "4",
          "6",
          "8",
          "10",
          "12",
          "14",
          "16",
          "18",
          "20",
        ],
        xdata: [
          "2024-01-11 12:00",
          "2024-01-11 12:02",
          "2024-01-11 12:04",
          "2024-01-11 12:06",
          "2024-01-11 12:08",
          "2024-01-11 12:10",
          "2024-01-11 12:12",
          "2024-01-11 12:14",
          "2024-01-11 12:16",
          "2024-01-11 12:18",
          "2024-01-11 12:20",
        ],
        ydata: [250, 380, 515, 243, 280, 500, 280, 540, 243, 280, 260],
      };
    },
  },
});
const { seriesData, showName, nameRotate, size } = toRefs(props);
const option = ref();
const lineEChartsRef = ref();

const xStandard = ref("");

// 折线图数据变更
watch(
  () => seriesData.value,
  (newVal) => {
    if (newVal?.xdata && newVal?.xdata.length && newVal?.index != null) {
      xStandard.value = newVal?.xdata[newVal?.index - 1] ?? "";
    } else {
      xStandard.value = "";
    }

    setOptions();
  },
  {
    deep: true,
    immediate: true,
  }
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工单管理详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function handleClick(param: any) {
  const id = seriesData.value.workOrderData[param.dataIndex] ?? "";
  if (id) {
    openDialogdetail({ id });
  }
}
// 计算y轴最小值
function computedMin(minValue: number, maxValue: number) {
  if (
    seriesData.value?.lowerLimitValue &&
    seriesData.value?.lowerLimitValue < minValue
  ) {
    return seriesData.value?.lowerLimitValue;
  } else if (minValue || maxValue) {
    const result = new Big(minValue)
      .minus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
    if (result < 0 && minValue >= 0) {
      return 0;
    } else {
      return result;
    }
  } else {
    return minValue;
  }
}

// 计算y轴最大值
function computedMax(maxValue: number, minValue: number) {
  if (!seriesData.value?.upperLimitValue && maxValue) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else if (
    (minValue || maxValue) &&
    seriesData.value?.upperLimitValue &&
    seriesData.value?.upperLimitValue < maxValue
  ) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else {
    return seriesData.value?.upperLimitValue;
  }
}

function setOptions() {
  option.value = {
    animation: true,
    // animationDuration: 3 * 100,
    color: ["#5470c6", "rgb(45, 93, 231)", "#15b3ff", "rgb(69,108,244)"],
    tooltip: {
      trigger: "axis",
      formatter: function (value: any) {
        return `${showName.value ? value[0].seriesName + "<br />" : ""}第${
          value[0].dataIndex + 1
        }个节点<br /> 采集时间：${
          seriesData.value.xdata[value[0].dataIndex]
        }<br />采集结果： ${value[0].marker}${value[0].data}`;
      },
      textStyle: {
        align: "left",
        fontSize: 14,
        fontFamily: "DINAlt",
        lineHeight: 30,
      },
    },
    grid: {
      left: size.value == "small" ? "4%" : "7%",
      top: size.value == "small" ? "50" : "70",
      right: 60,
      height: "auto",
      // minHeight: 400, // 单位为像素
      bottom: "5%",
      containLabel: true,
    },
    title: {
      text: seriesData.value.paramName || "",
      textStyle: {
        align: "center",
        fontSize: size.value == "small" ? 14 : 16,
        // fontFamily: "DINLight",
      },
      top: "0%",
      left: "center",
    },
    xAxis: {
      type: "category",
      // data: seriesData.value.xdataIndex || [],
      data: seriesData.value.xdata || [],
      axisLabel: {
        interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
        rotate: nameRotate.value, // 调整数值改变倾斜的幅度（范围-90到90）
        fontSize: 12,
        // fontFamily: "DINLight",
      },
      axisTick: {
        alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
      },
    },
    yAxis: {
      type: "value", // 坐标轴类型:数值轴
      // name: "湿度", // 坐标轴名称
      boundaryGap: false,
      // scale: true,
      min: function (value: any) {
        return computedMin(value.min, value.max);
      },
      max: function (value: any) {
        return computedMax(value.max, value.min);
      },
      position: "left", // 坐标轴位置:左侧
      // axisLabel: {
      //   interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
      //   // 调整数值改变倾斜的幅度（范围-90到90）
      // },
      // interval: "auto", // 坐标轴刻度间隔(当前被注释掉)
      offset: 0, // 坐标轴相对于默认位置的偏移:无偏移
      axisLine: {
        show: true, // 是否显示坐标轴线
        lineStyle: {
          color: "#6e7079", // 坐标轴线颜色:使用颜色数组的第一个颜色
        },
      },
      axisLabel: {
        fontSize: 12,
        // fontFamily: "DINLight",
        // 自定义标签显示：当布尔类型图表，则显示 true or false
        formatter: function (value: number) {
          return value;
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true, // 是否显示分隔线
        lineStyle: {
          type: "dotted", // 分隔线类型:点线
        },
      },
    },
    dataZoom: [
      // {
      //   type: "slider", // 滑动条型数据区域缩放
      //   start: 0,
      //   end: 100,
      // },
      {
        type: "inside", // 内置型数据区域缩放
        start: 0,
        end: 100,
      },
    ],
    series: {
      name: `${seriesData.value.paramName || ""}`,
      type: "line",
      data: seriesData.value.ydata || [],
      // label: {
      //   // 自定义标签显示：当布尔类型图表，则显示 true or false
      //   formatter: function (obj: any) {
      //     obj.value;
      //     // console.log(obj);
      //   },
      // },
      markPoint: {
        data:
          size.value == "small"
            ? []
            : [
                {
                  type: "max",
                },
                {
                  type: "min",
                },
              ],
      },
      markLine: {
        silent: true,
        data: [
          {
            show: xStandard.value ? true : false,
            name: "当前",
            xAxis: xStandard.value || "",
            label: {
              formatter: function (param) {
                // console.log("param", param);
                return (
                  "当前 " +
                  seriesData.value.ydata[seriesData.value?.index - 1 ?? 0]
                );
              },
            },
          },
          {
            name: "",
            yAxis: `${seriesData.value?.parameterStandards || null}`,
            lineStyle: {
              color: "rgb(29, 233, 182)",
              type: "dashed",
              width: 1,
            },
            label: {
              show: true,
              position: "end",
              formatter: "标准线",
            },
          },
          // {
          //   name: "",
          //   yAxis: `${seriesData.value?.upperLimitValue || null}`,
          //   lineStyle: {
          //     color: "rgb(248, 113, 113)",
          //     type: "dashed",
          //     width: 1,
          //   },
          //   label: {
          //     show: false,
          //     position: "end",
          //     formatter: "上限",
          //   },
          // },
          // {
          //   name: "",
          //   yAxis: `${seriesData.value?.lowerLimitValue || null}`,
          //   lineStyle: {
          //     color: "rgb(248, 113, 113)",
          //     type: "dashed",
          //     width: 1,
          //   },
          //   label: {
          //     show: false,
          //     position: "end",
          //     formatter: "下限",
          //   },
          // },
          {
            name: "",
            yAxis: `${seriesData.value?.controlUp || null}`,
            lineStyle: {
              color: "#ffd300",
              type: "dashed",
              width: 1,
            },
            label: {
              show: true,
              position: "end",
              formatter: "预警上限",
              // padding: 10,
              // distance: 20,
              // lineHeight: 70,
            },
            // label: {
            //   show: false,
            //   position: "end",
            //   formatter: ``,
            // },
            // emphasis: {
            //   label: {
            //     show: true,
            //     lineHeight: 70,
            //     fontSize: 14,
            //     position: "end",
            //     distance: 20,
            //     padding: 10,
            //     formatter: `预警上限`,
            //   },
            // },
          },
          {
            name: "",
            yAxis: `${seriesData.value?.controlDown || null}`,
            lineStyle: {
              color: "#ffd300",
              type: "dashed",
              width: 1,
            },
            label: {
              show: true,
              position: "end",
              formatter: "预警下限",
            },
          },
        ],
        symbol: "none",
      },
      symbol: "circle",
      symbolSize: 6,
      lineStyle: {
        width: 1.5,
      },
      // itemStyle: {
      //   normal: {
      //     // 定义点的颜色
      //     color: function (params) {
      //       // params是当前点的信息，可以根据条件返回不同的颜色
      //       if (
      //         params.value >= seriesData.value.upperLimitValue ||
      //         params.value <= seriesData.value.lowerLimitValue
      //       ) {
      //         return "#f56c6c"; // 如果值大于1000，点的颜色为红色
      //       } else if (
      //         params.value >= seriesData.value.controlUp ||
      //         params.value <= seriesData.value.controlDown
      //       ) {
      //         console.log(params.value, params);
      //         return "#ffd300"; // 否则为绿色
      //       } else {
      //         return "#4A95FF"; // 否则为绿色
      //       }
      //     },
      //   },
      // },
    },
    visualMap: isGetPieces(seriesData.value)
      ? [
          {
            show: false,
            pieces: getPieces(seriesData.value),
            seriesIndex: 0,
          },
        ]
      : null,
  };
}

onMounted(() => {});
</script>

<style lang="scss" scoped>
.echarts {
  width: 100%;
  height: 420px;
}

.echarts:nth-last-child(1) {
  border-bottom: none !important;
}
</style>
